/**
 * 
 */
package com.ws.framework.api;

import java.util.Map;
import java.util.Objects;

import org.apache.curator.shaded.com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ws.framework.controller.BaseController;
import com.ws.framework.model.App;
import com.ws.framework.model.Code;
import com.ws.framework.service.AppService;
import com.ws.framework.service.CodeService;
import com.ws.framework.util.ValidationUtil;

/**
 * <p>
 * </p>
 *
 * @author WSH
 */
@Controller
@RequestMapping("api")
public class ApiContoller extends BaseController {

	@Autowired
	AppService appService;
	@Autowired
	CodeService codeService;

	@RequestMapping("getSourceByCode")
	public ResponseEntity<String> getSourceByCode(@RequestParam(value = "codeName") String codeName,
			@RequestParam(value = "appCode") String appCode, @RequestParam(value = "timeStamp") long timeStamp,
			@RequestParam(value = "mac") String mac) {
			Map<String, Object> paramMap = Maps.newHashMap();
			paramMap.put("appCode", appCode);
			paramMap.put("codeName", codeName);
			paramMap.put("timeStamp", timeStamp);
			App app = appService.selectAppByCode(appCode);
			if (app == null) {
				return new ResponseEntity<String>("该app未注册", HttpStatus.BAD_REQUEST);
			}
			ValidationUtil.validate(paramMap, app.getPriKey(), mac);
			Code code = codeService.selectByCodeName(codeName);
			if (Objects.isNull(code) || code.getAppId().longValue() != app.getId()) {
				return new ResponseEntity<String>("该查找到对应的源码", HttpStatus.BAD_REQUEST);
			}
			return new ResponseEntity<String>(code.getCodeContext(), HttpStatus.OK);
	}
}
